import React from 'react'
import { connect } from 'react-redux'
import { StyleSheet, View, Text, LayoutAnimation } from 'react-native'
import { UPDATE_IM } from 'src/store/actions/im'
import ChatPage from 'src/pageP/message/chat-page'
import PersonCell from 'src/components/person-cell/index2'
import CustomButton from 'src/components/button/CustomButton'
import { getUserArchiveBundle, talentPostCard } from 'src/utils/RequestAPI'
import { DismissLoading, ShowLoading } from 'src/utils/ToastUtil'
import { ScaleS, ScaleT, IS_IOS } from 'src/utils/ScreenUtil'
import NavigationUtil from 'src/utils/NavigationUtil'
import CustomImage from 'src/components/image/CustomImage'

const mapActiontoProps = dispatch => ({
  updateImState (payload) {
    dispatch({
      type: UPDATE_IM,
      payload: {
        ...payload
      }
    })
  }
})

@connect(
  ({ userinfo, im, BMineCenterStore, landmark }) => ({
    userinfo,
    company: BMineCenterStore.company,
    landmark,
    ...im
  }),
  mapActiontoProps
)
class BChatPage extends ChatPage {
  constructor (props) {
    super(props)
    this.isPageB = true
    this.state = {
      ...this.state,
      personItem: {}
    }
  }

  renderHeader () {
    const { cardShow } = this.state
    return (
      <View style={styles.container}>
        {this._returnCardView()}
        <CustomButton style={styles.bottomBtn} onPress={this._toggleCard}>
          <View style={styles.btnCenter}>
            <CustomImage
              style={styles.btnImg}
              source={cardShow ? require('src/imgC/message/card_hide_arrow.png') : require('src/imgC/message/card_show_arrow.png')}
            />
          </View>
        </CustomButton>
      </View>
    )
  }

  _returnCardView = () => {
    const { personItem, cardShow } = this.state
    if (cardShow) {
      return <CustomButton style={styles.boxBtnView} onPress={this._personClick} params={personItem}>
        <PersonCell
          style={styles.personCellView}
          item={personItem}
          landmark={this.props.landmark}
          showLocation={false}
          noBorderBottom={true}
          showMore={false}/>
      </CustomButton>
    } else {
      return <CustomButton style={styles.cardContainer} onPress={this._toggleCard}>
        <Text style={styles.cardText}>{personItem.userName}</Text>
      </CustomButton>
    }
  }

  activeSendMessage (status) {
    if (status) {
      const { jobItem } = this.state
      const { company } = this.props
      const msg = `你好，我们正在招（${company.simpleName || company.companyName}）${jobItem.category}，方便的话可以聊聊吗？`
      this.sendMsg(msg).then(() => {
        DismissLoading()
      })
    } else {
      DismissLoading()
    }
  }

  _personClick = (personItem) => {
    NavigationUtil.navigate('CResumeDetail', {
      userId: personItem.userId,
      showCommunicate: false
    })
  }

  _toggleCard = () => {
    const { cardShow } = this.state
    this.layoutAnimation()
    if (cardShow) {
      this.setState({
        cardShow: false
      })
    } else {
      this.setState({
        cardShow: true
      })
    }
  }

  getUserId () {
    const { userinfo: { B: { userId } } } = this.props
    return userId
  }

  getSelToID () {
    const { selToID } = this.props
    return selToID
  }

  getName () {
    const { company: { companyName } } = this.props
    return companyName
  }

  componentDidMount () {
    super.componentDidMount()
    const { selToID } = this.props
    // ShowLoading()
    getUserArchiveBundle({
      params: {
        userId: parseInt(selToID)
      }
    }).then((data) => {
      console.info(data.data)
      const item = this._generatePersonItem(data.data)
      this.setState({ personItem: item })
    }).finally(() => {
      // DismissLoading()
    })
    this._getJobDetail()
  }

  _getJobDetail = () => {
    // 获取岗位详情
    const { landmark: { cityName }, selToID } = this.props
    talentPostCard({
      params: {
        cUserId: parseInt(selToID),
        city: cityName,
        userId: this.getUserId()
      }
    }).then((data) => {
      this.setState({ jobItem: data.data })
    })
  }

  /**
   * 生成个人信息数据
   * @param data
   * @returns {{education: *, userName: *, comprehensive: *}}
   * @private
   */
  _generatePersonItem = (data) => {
    const { archive: { userArchiveModel = {}, jobHuntingModels = [] } = {}, education = [] } = data
    const comprehensive = jobHuntingModels.reduce((total, jobHuntingItem) => {
      const comprehensive = JSON.parse(jobHuntingItem.comprehensive)
      const { workNature, workCategory } = comprehensive
      total.workNature = total.workNature.concat(workNature)
      total.workCategory = total.workCategory.concat(workCategory)
      return total
    }, { workPlace: [], workNature: [], workCategory: [] })
    let highestDegree = 0
    education.forEach((item) => {
      highestDegree = item.degreeLevel > highestDegree ? item.degreeLevel : highestDegree
    })
    const item = {
      ...userArchiveModel,
      userName: userArchiveModel.name,
      education: highestDegree,
      comprehensive: JSON.stringify(comprehensive)
    }
    return item
  }

  layoutAnimation = () => {
    // 动画
    IS_IOS && LayoutAnimation.configureNext({
      duration: 220,
      create: {
        type: LayoutAnimation.Types.linear,
        property: LayoutAnimation.Properties.opacity
      },
      update: {
        type: LayoutAnimation.Types.easeInEaseOut
      }
    })
  }
}

export default BChatPage

const styles = StyleSheet.create({
  container: {
    minHeight: ScaleS(30)
  },
  cardContainer: {
    width: '100%',
    height: ScaleS(30),
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center'
  },
  cardText: {
    color: '#666666',
    fontSize: ScaleT(11)
  },
  boxBtnView: {
    backgroundColor: 'white',
    paddingBottom: ScaleS(10)
  },
  personCellView: {
    paddingTop: ScaleS(5),
    paddingHorizontal: ScaleS(5)
  },
  introStyle: {
    marginTop: ScaleS(5),
    lineHeight: ScaleS(20)
  },
  bottomView: {
    marginTop: ScaleS(0)
  },
  rightViewStyle: {
    paddingBottom: ScaleS(5)
  },
  bottomBtn: {
    width: '100%',
    height: ScaleS(10),
    alignItems: 'center',
    justifyContent: 'center'
  },
  btnCenter: {
    width: ScaleS(30),
    height: ScaleS(10),
    alignItems: 'center',
    justifyContent: 'center'
  },
  btnImg: {
    width: ScaleS(30),
    height: ScaleS(10),
    resizeMode: 'cover'
  }
})
